<?php
require_once("../../Config.php");
require_once("../../Class/ClassFunc.php");
require_once("../../Class/ClassMysql.php");
require_once("../../Class/ClassCheck.php");
require_once("../../Class/ClassResult.php");
require_once("../../Sdk/path_to_sdk/autoload.php");

//json头
header("Content-type: application/json");
// 引入鉴权类
use Qiniu\Auth;



session_start();
if(!isset($_SESSION["name"])) {
    exit(Result::jsonReturn(1, "未登录"));
}

$uid = (int)$_SESSION["id"];
$uname = $_SESSION["name"];
$uemail = $_SESSION["email"];
$upower = $_SESSION["power"];


if(Check::isEmpty($_POST["id"])) {
    exit(Result::jsonReturn(1, "参数不足"));
}
$id = 0;
if(Check::isNum($_POST["id"]) && (int)$_POST["id"]>0) {
    $id = (int)$_POST["id"];
}else {
    exit(Result::jsonReturn(1, "参数格式有误"));
}

$db = new DB();
$sql_sel = "SELECT attach.id FROM qilian_attachments as attach LEFT JOIN qilian_contents as cont".
           " ON attach.content_id=cont.id WHERE attach.id={$id} AND cont.user_id={$uid}";
if((int)$db->getRows($sql_sel) == 0) {
    exit(Result::jsonReturn(1, "当前用户没有此附件"));
}

$sql_get = "SELECT akey FROM qilian_attachments WHERE id={$id}";
$tmp = $db->getOne($sql_get);
delAttach($tmp['akey']);

$sql_del = "DELETE FROM qilian_attachments WHERE id={$id}";
if($db->delete($sql_del)) {
    exit(Result::jsonReturn(0, "删除附件成功", array(
        "id"=>(int)$id)));
}else {
    exit(Result::jsonReturn(1, "删除附件失败"));
}

function delAttach($key) {
    $accessKey = ACCESS_KEY;
    $secretKey = SECRET_KEY;
    $bucket = BUCKET;
    $key = $key;
    $auth = new Auth($accessKey, $secretKey);
    $config = new \Qiniu\Config();
    $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
    $err = $bucketManager->delete($bucket, $key);
}
?>